import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_learn_vi/src/bean/bean_common_config.dart';
import 'package:flutter_learn_vi/src/bean/bean_global.dart';
import 'package:flutter_learn_vi/src/bean/bean_news.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/global.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/model/user_model.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/bloc/bloc_select_page.dart';
import 'package:flutter_learn_vi/src/page/mine/question_model.dart';
import 'package:flutter_learn_vi/src/page/news/news_item2_page.dart';
import 'package:flutter_learn_vi/src/page/news/study_dongtai_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_select_page.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'home_item_study_widget.dart';
import 'kuang_eails_page.dart';

//lib/src/page/home/home_item_page.dart
//首页面显示的视频列表播放页面
//首页面显示的视频列表播放页面
class HomeItemMainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MainFindPage3State();
  }
}

//使用到[TabBar] 所以要绑定一个Ticker
//当前页面被装载在[PageView]中，使用KeepAlive使用页面保持状态
class MainFindPage3State extends State
    with
        AutomaticKeepAliveClientMixin,
        SingleTickerProviderStateMixin,
        UserModel,
        MineQuestionModel {
  //页面保持状态
  @override
  bool get wantKeepAlive => true;

  //在这里标签页面使用的是TabView所以需要创建一个控制器
  TabController _tabController;

  //页面初始化方法
  @override
  void initState() {
    super.initState();
    int isCheck = UserHelper.getInstance.userBean.isCheck;
    if (isCheck == 1) {
      //初始化
      _tabController = new TabController(length: 1, vsync: this);
    } else {
      //初始化
      //集团权限
      if (UserHelper.getInstance.userBean.userBlocType == 1) {
        _tabController = new TabController(length: 4, vsync: this);
      } else {
        _tabController = new TabController(length: 3, vsync: this);
      }
    }

    rootStreamController.stream.listen((event) {
      if (event.code == 204) {
        isStudyModel = event.data;
        Future.delayed(Duration.zero, () {
          setState(() {});
        });
      }
    });

    getNewsList();
  }

  //页面销毁回调生命周期
  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  List<NewsBean> newsList = [];
  List<NewsBean> dangjianList = [];

  //有领导信箱的内容
  double _defaultHeader = 290;

  ///是否加载学习版块
  bool isStudyModel = false;

  //无
  double _defaultHeader2 = 230;

  Future<bool> getNewsList() async {
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.newslistV3 + "?homenews=Y",
    );
    if (responseInfo.success) {
      List list = responseInfo.data;

      list.forEach((element) {
        NewsBean newsBean = NewsBean.fromJson(element);
        newsList.add(newsBean);
      });
    }

    ResponseInfo partResponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.newslistV2 + "?partbuild=Y",
    );
    if (partResponseInfo.success) {
      List list = partResponseInfo.data;

      list.forEach((element) {
        NewsBean newsBean = NewsBean.fromJson(element);
        dangjianList.add(newsBean);
      });
    }

    ResponseInfo integralResponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.commonConfigUrl,
    );
    if (partResponseInfo.success) {
      List list = integralResponseInfo.data;
      List<CommonConfigBean> configList = [];
      if (list != null && list.length > 0) {
        list.forEach((element) {
          CommonConfigBean commonConfigBean = CommonConfigBean.fromMap(element);
          configList.add(commonConfigBean);
        });
      }
      UserHelper.getInstance.configList = configList;
    }
    getQuestion();

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }

  ///代码清单 5-19 NestedScrollView 下拉刷新
  ///lib/code/code5/example_504_CustomScrollView.dart
  @override
  Widget build(BuildContext context) {
    super.build(context);
    //构建页面的主体
    return Scaffold(
      //下拉刷新
      body: RefreshIndicator(
        //可滚动组件在滚动时会发送ScrollNotification类型的通知
        notificationPredicate: (ScrollNotification notifation) {
          //该属性包含当前ViewPort及滚动位置等信息
          ScrollMetrics scrollMetrics = notifation.metrics;
          if (scrollMetrics.minScrollExtent == 0) {
            return true;
          } else {
            return false;
          }
        },
        //下拉刷新回调方法
        onRefresh: () async {
          //模拟网络刷新 等待2秒
          await getUserInfo();
          await getNewsList();
          await getQuestion();
          rootStreamController.add(GlobalBean(203, null));
          ToastUtils.showToast("已刷新");
          //返回值以结束刷新
          return Future.value(true);
        },
        child: buildNestedScrollView(),
      ),
    );
  }

  ///代码清单 5-20 NestedScrollView 的创建
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildNestedScrollView() {
    if (UserHelper.getInstance.userBean == null) {
      return Container();
    }
    int isCheck = UserHelper.getInstance.userBean.isCheck;
    List<Widget> tabBarViewList = [];
    if (isCheck == 1) {
      tabBarViewList = [StudyDongTaiItemPage()];
    } else {
      tabBarViewList = [
        StudyDongTaiItemPage(),
        NewsHomeItemPage(list: newsList),
        NewsHomeItemPage(
          list: dangjianList,
          clickCallback: () async {
            await getNewsList();
            ToastUtils.showToast("已刷新");
          },
        ),
      ];

      //集团权限
      if (UserHelper.getInstance.userBean.userBlocType == 1) {
        tabBarViewList.add(BlocSelectPage());
      }
    }
    //滑动视图
    return NestedScrollView(
      //配置可折叠的头布局
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [buildSliverAppBar()];
      },
      //页面的主体内容
      body: TabBarView(
        controller: _tabController,
        children: tabBarViewList,
      ),
    );
  }

  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildSliverAppBar() {
    double _currentHeight = _defaultHeader;
    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean.userType != 1) {
      _currentHeight = _defaultHeader2;
    }
    if (isStudyModel) {
      _currentHeight += 100;
    }
    return SliverAppBar(
      //第一部分 标题 这里是搜索框
      title: buildHeader(),
      //标题居中
      centerTitle: true,
      //5.1.2小节中有对这一块的属性配置说明
      pinned: true,
      floating: false,
      snap: false,
      //阴影高度
      elevation: 0.0,
      //展开的高度
      expandedHeight: _currentHeight,
      //第二部分 AppBar下的内容区域
      flexibleSpace: FlexibleSpaceBar(
        //背景
        //配置的是一个widget也就是说在这里可以使用任意的
        //Widget组合 在这里直接使用的是一个图片
        background: buildFlexibleSpaceWidget(),
      ),
      //第三部分
      bottom: buildFlexibleTooBarWidget(),
    );
  }

  ///代码清单 5-23 构建SliverAppBar的标题title
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildHeader() {
    if (UserHelper.getInstance.mineBean == null) {
      return Container();
    }
    return Container(
      //宽度填充
      width: double.infinity,
      //左边距
      padding: EdgeInsets.only(left: 10),
      //高度限制
      height: 38,
      //左右排列的线性布局
      child: Stack(
        children: [
          Positioned(
            left: 0,
            right: 0,
            child: Row(
              children: [
                Material(
                  color: Colors.transparent,
                  child: ClipOval(
                    child: buildHeaderImage(),
                  ),
                )
              ],
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            child: Text(
              UserHelper.getInstance.mineBean.name,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildHeaderImage() {
    if (UserHelper.getInstance.mineBean == null) {
      return Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    String url = UserHelper.getInstance.mineBean.logoUrl;

    if (url == null || url.length == 0) {
      Image.asset(
        "assets/images/3.0x/bg_header.png",
        fit: BoxFit.fill,
        width: 33,
        height: 33,
      );
    }
    return CachedNetworkImage(
      imageUrl: url,
      fit: BoxFit.fill,
      width: 33,
      height: 33,
    );
  }

  ///代码清单 5-24 FlexibleSpaceBar 中的内容
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildFlexibleSpaceWidget() {
    //上下排列的线性布局
    return Container(
      color: Colors.grey[200],
      child: Stack(
        children: [
          //第一部分是一个 轮播图
          Container(
            height: 270,
            width: MediaQuery.of(context).size.width,
            child: Image.asset(
              "assets/images/3.0x/home_wh_yin.png",
              fit: BoxFit.fill,
            ),
          ),
          Positioned(
            left: 12,
            top: 93,
            right: 16,
            child: Column(
              children: [
                //第二部分是左右排列的两个图标
                buildRightClassWidget(),
                //领导信箱
                buildEamils(),
                HomeitemStudyWidget(),
              ],
            ),
          )
        ],
      ),
    );
  }

  Container buildEamils() {
    UserBean userBean = UserHelper.getInstance.userBean;
    if (userBean.userType != 1) {
      return Container();
    }
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(4))),
      child: GestureDetector(
        onTap: () {
          NavigatorUtils.pushPage(context, EamilsListPage());
        },
        child: Row(
          children: [
            Image.asset(
              "assets/images/3.0x/icon_4.png",
              fit: BoxFit.fill,
              width: 66,
              height: 66,
            ),
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 12, right: 12),
                child: Text(
                  "暂无最新反馈信息",
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.grey, fontSize: 14),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  ///代码清单 5-25 FlexibleSpaceBar 中的内容
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildRightClassWidget() {
    return Container(
      height: 100,
      child: Row(
        children: [
          //两个等比排开
          buildHeaderClass(
              image: "assets/images/3.0x/icon_2.png",
              text: "每日必答",
              onTap: () {
                //EVERYDAY
                //QUICK_PRACTICE
                NavigatorUtils.pushPage(
                  context,
                  TopicSelectPage(
                    pageTitle: "每日必答",
                    categoryOne: "EVERYDAY",
                  ),
                );
              }),
          SizedBox(
            width: 20,
          ),
          //两个等比排开
          buildHeaderClass(
              image: "assets/images/3.0x/icon_1.png",
              text: "日常练习",
              onTap: () {
                NavigatorUtils.pushPage(
                  context,
                  TopicSelectPage(
                    pageTitle: "日常练习",
                    categoryOne: "QUICK_PRACTICE",
                  ),
                ); // NavigatorUtils.openPageByFade(context, TopicEndPage());
              }),
        ],
      ),
    );
  }

  Expanded buildHeaderClass({@required String image, @required String text, Function onTap}) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          height: 60,
          decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.4),
              borderRadius: BorderRadius.all(Radius.circular(4))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                image,
                fit: BoxFit.fill,
                width: 38,
                height: 38,
              ),
              SizedBox(
                width: 10,
              ),
              Text(
                text,
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///代码清单 5-26 [SliverAppBar]的bottom属性配制
  ///lib/code/code5/example_504_CustomScrollView.dart
  Widget buildFlexibleTooBarWidget() {
    int isCheck = UserHelper.getInstance.userBean.isCheck;
    List<Tab> tabList = [];
    if (isCheck == 1) {
      tabList = [
        new Tab(
          text: "最新动态",
        ),
      ];
    } else {
      tabList = [
        new Tab(
          text: "最新动态",
        ),
        new Tab(
          text: "最新消息",
        ),
        new Tab(
          text: "最新推荐",
        ),
      ];
      //集团权限
      if (UserHelper.getInstance.userBean.userBlocType == 1) {
        tabList.add(
          Tab(
            text: "集团中心",
          ),
        );
      }
    }

    //[PreferredSize]用于配置在AppBar或者是SliverAppBar
    //的bottom中 实现 PreferredSizeWidget
    return PreferredSize(
      //定义大小
      preferredSize: Size(MediaQuery.of(context).size.width, 44),
      //配置任意的子Widget
      child: Container(
        alignment: Alignment.center,
        child: Container(
          color: Colors.white,
          //随着向上滑动，TabBar的宽度逐渐增大
          //父布局Container约束为 center对齐
          //所以程现出来的是中间x轴放大的效果
          width: MediaQuery.of(context).size.width,
          child: TabBar(
            //指示线的宽度与文本宽度一致
            indicatorSize: TabBarIndicatorSize.label,
            //指示线的颜色
            indicatorColor: Colors.redAccent,
            //未选中文本的颜色
            unselectedLabelColor: Colors.grey,
            //选中文本的颜色
            labelColor: Colors.redAccent,
            controller: _tabController,
            tabs: tabList,
          ),
        ),
      ),
    );
  }
}
